#  LOF基金行情

import requests
from datetime import datetime
import os
import json

# 获取当前文件名（不包括扩展名）
script_path = os.path.abspath(__file__)
filename = os.path.splitext(os.path.basename(script_path))[0]

# 打印文件名
print(f"当前文件名: {filename}")

# 获取当前日期作为文件夹名，8位格式
current_date_folder = datetime.now().strftime("%Y%m%d")

# 获取当前脚本的父级目录的同级目录
parent_dir = os.path.dirname(os.path.dirname(script_path))

# 创建同级目录下的以日期命名的文件夹路径
target_dir = os.path.join(parent_dir, current_date_folder)

# 如果文件夹不存在则创建
os.makedirs(target_dir, exist_ok=True)

# API 请求的 URL 和参数
url = "https://65.push2.eastmoney.com/api/qt/clist/get"
params = {
    # "cb": "jQuery1124019268949016785641_1714784134039",
    "pn": 1,
    "pz": 20,
    "po": 1,
    "np": 1,
    "ut": "bd1d9ddb04089700cf9c27f6f7426281",
    "fltt": 2,
    "invt": 2,
    "wbp2u": "|0|0|0|web",
    "fid": "f3",
    "fs": "b:MK0404,b:MK0405,b:MK0406,b:MK0407",
    "fields": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152",
    "_": 1714784134047
}


# 发送 GET 请求
response = requests.get(url, params=params)

if response.status_code == 200:
    data = response.json()

    # 创建保存完整 JSON 响应的文件名
    file_name_txt = f"{filename}.txt"
    full_file_path_txt = os.path.join(target_dir, file_name_txt)

    # 保存完整的 JSON 响应到文件
    with open(full_file_path_txt, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)
    print(f"完整数据已写入到文件: {full_file_path_txt}")

    # 提取 `diff` 数据
    diff_data = data.get('data', {}).get('diff', [])

    # 创建保存提取 `diff` 数据的文件名
    file_name_json = f"{filename}.json"
    full_file_path_json = os.path.join(target_dir, file_name_json)

    # 保存提取的 `diff` 数据到文件
    with open(full_file_path_json, 'w', encoding='utf-8') as file:
        json.dump(diff_data, file, ensure_ascii=False, indent=4)
    print(f"提取数据已写入到文件: {full_file_path_json}")

else:
    print(f"请求失败: {response.status_code}")
